package cn.lili.controller.member;

import cn.lili.common.aop.annotation.DemoSite;
import cn.lili.common.enums.ResultCode;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.security.AuthUser;
import cn.lili.common.security.context.UserContext;
import cn.lili.common.enums.ResultUtil;
import cn.lili.common.vo.PageVO;
import cn.lili.common.vo.ResultMessage;
import cn.lili.common.vo.SearchVO;
import cn.lili.modules.member.entity.dos.Member;
import cn.lili.modules.member.service.MemberService;
import cn.lili.modules.permission.entity.dos.AdminUser;
import cn.lili.modules.permission.entity.dos.StoreUser;
import cn.lili.modules.permission.entity.dto.AdminUserDTO;
import cn.lili.modules.permission.entity.vo.AdminUserVO;
import cn.lili.modules.permission.entity.vo.StoreUserVO;
import cn.lili.modules.permission.service.StoreUserService;
import cn.lili.modules.store.serviceimpl.StoreServiceImpl;
import cn.lili.mybatis.util.PageUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 店铺端,管理员接口
 *
 * @author Chopper
 * @since 2020/11/16 10:57
 */
@RestController
@Api(tags = "店铺端,管理员接口")
@RequestMapping("/store/user")
public class StoreUserController {
	@Autowired
	private MemberService memberService;

	@Autowired
	private StoreUserService storeUserService;
	private Logger log = LoggerFactory.getLogger(StoreServiceImpl.class);

	@RequestMapping(value = "/info")
	@ApiOperation(value = "获取当前登录用户接口")
	public ResultMessage<Member> getUserInfo() {
		AuthUser tokenUser = UserContext.getCurrentUser();
		if (tokenUser != null) {
			Member member = memberService.findByUsername(tokenUser.getUsername());
			member.setPassword(null);
			return ResultUtil.data(member);
		}
		throw new ServiceException(ResultCode.USER_NOT_LOGIN);
	}

	@GetMapping
	@ApiOperation(value = "多条件分页获取用户列表")
	public ResultMessage<IPage<StoreUserVO>> getByCondition(AdminUserDTO user, SearchVO searchVo, PageVO pageVo) {
		IPage<StoreUserVO> page = storeUserService.StoreUserPage(PageUtil.initPage(pageVo),
				PageUtil.initWrapper(user, searchVo));
		return ResultUtil.data(page);
	}

	@PutMapping(value = "/enable/{userId}")
	@ApiOperation(value = "禁/启 用 用户")
	@DemoSite
	public ResultMessage<Object> disable(@ApiParam("用户唯一id标识") @PathVariable String userId, Boolean status) {
		StoreUser user = storeUserService.getById(userId);
		if (user == null) {
			throw new ServiceException(ResultCode.USER_NOT_EXIST);
		}
		user.setStatus(status);
		storeUserService.updateById(user);
		return ResultUtil.success();
	}

	@PostMapping
	@ApiOperation(value = "添加用户")
	public ResultMessage<Object> register(@Valid StoreUser storeUser,
			@RequestParam(required = false) List<String> roles) {
		int rolesMaxSize = 10;
		try {
			AuthUser currentUser = UserContext.getCurrentUser();
			StoreUser one = storeUserService
					.getOne(new LambdaQueryWrapper<StoreUser>().eq(StoreUser::getId, currentUser.getId()));
			storeUser.setParentId(one.getId()); // 上级ID
			storeUser.setMemberId(one.getMemberId()); // 上级店铺会员ID
			storeUser.setStoreId(one.getStoreId());// 上级店铺ID
			storeUser.setRoleIds(roles.get(0)); // 角色
			if (roles != null && roles.size() >= rolesMaxSize) {
				throw new ServiceException(ResultCode.PERMISSION_BEYOND_TEN);
			}
			// 判断用户名是否存在
			if (storeUserService.getOne(
					new LambdaQueryWrapper<StoreUser>().eq(StoreUser::getUsername, storeUser.getUsername())) != null) {
				throw new ServiceException(ResultCode.USER_NAME_EXIST);
			}
			// 判断手机号是否存在
			if (storeUserService.getOne(
					new LambdaQueryWrapper<StoreUser>().eq(StoreUser::getMobile, storeUser.getMobile())) != null) {
				throw new ServiceException(ResultCode.USER_PHONE_EXIST);
			}
			storeUser.setPassword(new BCryptPasswordEncoder().encode(storeUser.getPassword()));
			storeUserService.save(storeUser);
		} catch (Exception e) {
			log.error("添加用户错误", e);
		}
		return ResultUtil.success();
	}

	@PutMapping(value = "/edit")
	@ApiOperation(value = "修改用户自己资料", notes = "用户名密码不会修改")
	public ResultMessage<Object> editOwner(StoreUser storeUser) {

		AuthUser tokenUser = UserContext.getCurrentUser();
		if (tokenUser != null) {
			// 查询当前管理员
			StoreUser one = storeUserService
					.getOne(new LambdaQueryWrapper<StoreUser>().eq(StoreUser::getUsername, storeUser.getUsername()));
			one.setAvatar(storeUser.getAvatar());
			one.setNickName(storeUser.getNickName());
			if (!storeUserService.updateById(one)) {
				throw new ServiceException(ResultCode.USER_EDIT_ERROR);
			}
			return ResultUtil.success(ResultCode.USER_EDIT_SUCCESS);
		}
		throw new ServiceException(ResultCode.USER_NOT_LOGIN);
	}

	@PutMapping(value = "/admin/edit")
	@ApiOperation(value = "超级管理员修改其他管理员资料")
	@DemoSite
	public ResultMessage<Object> edit(@Valid StoreUser storeUser, @RequestParam(required = false) List<String> roles) {
		if (roles.size() > 0) {
			storeUser.setRoleIds(roles.get(0));
		}
		if (!storeUserService.updateById(storeUser)) {
			throw new ServiceException(ResultCode.USER_EDIT_ERROR);
		}
		return ResultUtil.success(ResultCode.USER_EDIT_SUCCESS);
	}

	@DeleteMapping(value = "/{ids}")
	@ApiOperation(value = "批量通过ids删除")
	@DemoSite
	public ResultMessage<Object> delAllByIds(@PathVariable List<String> ids) {
		storeUserService.deleteCompletely(ids);
		return ResultUtil.success();
	}

	@RequestMapping(value = "/resetPassword/{ids}")
	@ApiOperation(value = "重置密码")
	@DemoSite
	public ResultMessage<Object> resetPassword(@PathVariable List ids) {
		storeUserService.resetPassword(ids);
		return ResultUtil.success(ResultCode.USER_EDIT_SUCCESS);
	}
}
